# coding=utf-8
import base64
import random
import string
import uuid

from captcha.image import ImageCaptcha

from sutras.utils import redis_service


def generate_captcha():
    """
    生成验证码

    返回：
        (captcha_img, captcha_text)
        captcha_img: 验证码图片，BytesIO对象
        captcha_text: 验证码文字
    """
    seq = string.ascii_letters + string.digits
    tmp_chars = []
    for i in range(4):
        tmp_chars.append(random.choice(seq))
    captcha_text = "".join(tmp_chars)
    image = ImageCaptcha()
    captcha_img = image.generate(captcha_text)
    return captcha_img, captcha_text


def generate_login_captcha():
    """
    生成登录验证码

    返回：
        (login_id, b64_captcha_img)
        login_id: 登录ID，需要种在cookie里
        b64_captcha_img: 验证码图片base64后字符串
    """
    captcha_img, captcha_text = generate_captcha()
    cache = redis_service.LoginCaptcha()
    login_id = uuid.uuid1().hex
    cache.set(login_id, captcha_text)
    b64_captcha_img = base64.b64encode(captcha_img.getvalue())
    return login_id, b64_captcha_img


def get_captcha_text(login_id):
    """
    获取验证码文本
    """
    cache = redis_service.LoginCaptcha()
    return cache.get(login_id)
